<!DOCTYPE html>
<html lang="zh" xmlns:th="http://www.thymeleaf.org" >
<head>
	<th:block th:include="include :: header('修改商品')" />
	<th:block th:include="include :: bootstrap-fileinput-css" />
	<th:block th:include="include :: summernote-css" />
	<style>
		.modal-content{
			z-index: 30000;
		}

		.file-preview-frame.is-selected {
			border: 1px solid #f30;
		}

		.file-preview-frame.is-selected:after {
			content: '默认图';
			width: 60px;
			height: 20px;
			line-height: 20px;
			text-align: center;
			background-color: #f30;
			color: #fff;
			position: absolute;
			left: 0;
			top: 0;
		}

		/**
       商品规格样式
       */

		.ws-goodsstyle__panel {
			border: 1px solid #DAE3E6;
			background: #F5F8FA;
			margin-left:15px;
		}

		.ws-goodsstyle__panel .tit {
			margin: 5px;
			font-weight: bold;
			clear: both;
		}

		.ws-goodsstyle__panel li {
			float: left;
		}

		.ws-goodsstyle__panel li:not(.tit) {
			background: #f9f9f9;
			border: 1px solid #a9a9a9;
			padding: 2px 5px;
			/*margin: 5px;*/
			margin-left: 8px;
		}
	</style>
</head>
<body class="white-bg">
    <div class="wrapper wrapper-content animated fadeInRight ibox-content">
        <form class="form-horizontal m" id="form-goods-edit" th:object="${goods}">
            <input id="goodsId" name="goodsId" th:field="*{goodsId}"  type="hidden">
				<input name="catId" type="hidden" th:field="*{catId}" id="treeId"/>
				<input name="typeId" type="hidden" th:field="*{typeId}" id="typeId"/>
				<input id="imageDefaultId" type="hidden" name="imageDefaultId" th:field="*{imageDefaultId}"> <br>
				<input id="imageIds" type="hidden" name="imageIds" th:field="*{imageIds}">
				<h4 class="form-header h4">基本信息</h4>
				<div class="row">

					<div class="col-md-6">
						<div class="form-group">
							<label class="col-sm-3 control-label"><span style="color: red; ">*</span>商品名称：</label>
							<div class="col-sm-9">
								<input type="text" name="name" class="form-control" placeholder="请输入商品名称" th:field="*{name}"  maxlength="30" required>
							</div>
						</div>
					</div>

					<div class="col-md-6">
						<div class="form-group">
							<label class="col-sm-3 control-label"><span style="color: red; ">*</span>分类：</label>
							<div class="col-sm-8">
								<div class="input-group">
									<input  onclick="selectGoodsTree()" id="treeName" name="catName" th:field="*{catName}"   type="text" placeholder="请选择归属分类" class="form-control" required>
									<span class="input-group-addon"><i class="fa fa-search"></i></span>
								</div>
							</div>
						</div>
					</div>

				</div>

				<div class="row">
					<div class="col-md-6">
						<div class="form-group">
							<label class="col-sm-3 control-label"><span style="color: red; ">*</span>类型：</label>
							<div class="col-sm-9">
								<input id="typeName" type="text"   name="typeName" th:field="*{typeName}" readonly class="form-control" required
									   placeholder="请输入类型">
							</div>
						</div>
					</div>

					<div class="col-md-6">
						<div class="form-group">
							<label class="col-sm-3 control-label">品牌：</label>
							<div class="col-sm-9">
								<select name="brandId" data-role="brand" th:field="*{brandId}" class="form-control noselect2 selectpicker" data-none-selected-text="请选择品牌"
										data-live-search="true">
								</select>
							</div>
						</div>
					</div>
				</div>

			<div class="col-md-12" style="margin-left: -160px">
				<div class="form-group">
					<label class="col-sm-3 control-label">商品相册：</label>
					<div class="col-sm-9">
						<input id="goodsPicture" name="file" type="file" multiple>
					</div>
				</div>
			</div>


			<div id="goodsBasic">

				<div class="row">
					<div class="col-md-6">
						<div class="form-group">
							<label class="col-sm-3 control-label"><span style="color: red; ">*</span>销售价：</label>
							<div class="col-sm-9">
								<input type="text" name="price" class="form-control" th:field="*{price}" placeholder="请输入商品价格"  maxlength="30" required>
							</div>
						</div>
					</div>
					<div class="col-md-6">
						<div class="form-group">
							<label class="col-sm-3 control-label"><span style="color: red; ">*</span>货号：</label>
							<div class="col-sm-9">
								<input type="text" name="bn" th:field="*{bn}" class="form-control" placeholder="请输入商品货号" required>
							</div>
						</div>
					</div>
				</div>

				<div class="row">
					<div class="col-md-6">
						<div class="form-group">
							<label class="col-sm-3 control-label">库存：</label>
							<div class="col-sm-9">
								<input type="text" name="store" class="form-control" th:field="*{store}" placeholder="请输入商品库存"  maxlength="10" required>
							</div>
						</div>
					</div>
					<div class="col-md-6">
						<div class="form-group">
							<label class="col-sm-3 control-label">货位：</label>
							<div class="col-sm-9">
								<input type="text" name="storePlace" th:field="*{storePlace}" class="form-control" placeholder="请输入货位" >
							</div>
						</div>
					</div>
				</div>

			</div>


			<div class="row" id="specBtn" style="display: none">
				<div class="col-md-6">
					<div class="form-group">
						<label class="col-sm-3 control-label"><button id="btnAdd" type="button" class="btn btn-primary btn-xs">开启规格</button></label>
						<label class="col-sm-7 control-label"><span style="color: red; ">开启规格前先填以上价格等信息，可自动复制信息到货品</span></label>
					</div>
				</div>

			</div>

			<div class="row" id="specDiv" style="display: none">
				<div class="col-md-6">
					<div class="form-group">
						<label class="col-sm-3 control-label"><button type="button" class="btn btn-primary btn-xs" id="btnEdit" data-role="product-edit">编辑规格</button></label>
						<div class="ws-goodsstyle__panel col-sm-6">
							<ul class="" data-role="spec-item">
								<li class="tit">已经启动的规格项:</li>
								<li>11</li>
								<li>11</li>
							</ul>
							<p class="tit" data-role="spec-tit">
								已生成货品(6)
							</p>
						</div>
						<label class="col-sm-3 control-label"><button type="button" class="btn btn-default btn-xs" id="btnClose" data-role="product-close">关闭</button></label>
					</div>
				</div>

			</div>
			<input name="specDesc" id="specDesc" th:field="*{specDesc}" type="hidden">


				<div class="hr-line-dashed">扩展属性</div>
				<div class="hide1" id="propsDiv">
				</div>

				<div class="hr-line-dashed"></div>

				<div class="row">
					<div class="col-md-6">
						<div class="form-group">
							<label class="col-sm-3 control-label">重量：</label>
							<div class="col-sm-9">
								<input type="text" name="weight" class="form-control" th:field="*{weight}" placeholder="请输入商品库存"  maxlength="10" >
							</div>
						</div>
					</div>
					<div class="col-md-6">
						<div class="form-group">
							<label class="col-sm-3 control-label">积分：</label>
							<div class="col-sm-9">
								<input type="text" name="score" th:field="*{score}" class="form-control" placeholder="请输入积分" >
							</div>
						</div>
					</div>
				</div>


				<div class="row">
					<div class="col-md-6">
						<div class="form-group">
							<label class="col-sm-3 control-label">商品简介：</label>
							<div class="col-sm-9">
								<textarea name="brief" th:field="*{brief}" class="form-control" placeholder="简短的商品介绍,请不要超过70个字"></textarea>
							</div>
						</div>
					</div>
				</div>

				<div class="hr-line-dashed"></div>

				<div class="row">
					<div class="col-md-6">
						<div class="form-group">
							<label class="col-sm-3 control-label">立即上架：：</label>
							<div class="col-sm-9">
								<input type="radio" checked="" value="true" id="optionsRadios1" name="marketable"> 是 &nbsp;
								<input type="radio" checked value="false" id="optionsRadios2" name="marketable"> 否 &nbsp;
							</div>
						</div>
					</div>
					<div class="col-md-6">
						<div class="form-group">
							<label class="col-sm-3 control-label">增加库存自动上架：</label>
							<div class="col-sm-9">
								<input type="radio" checked="" value="1" id="optionsRadios3" name="isAuto"> 是 &nbsp;
								<input type="radio" checked value="2" id="optionsRadios4" name="isAuto"> 否 &nbsp;
							</div>
						</div>
					</div>
				</div>

				<div class="hr-line-dashed"></div>


				<div class="form-group">
					<label class="col-sm-2 control-label">详细介绍：</label>
					<div class="col-sm-10">
						<input id="intro" name="intro" th:field="*{intro}" type="hidden">
						<div id="editor" class="summernote"></div>
					</div>
				</div>

			</form>
    </div>
    <div th:include="include::footer"></div>
	<th:block th:include="include :: bootstrap-fileinput-js" />
	<th:block th:include="include :: summernote-js" />
	<script th:inline="javascript">
		var prefix = ctx + "goods/goods";
		$("#form-goods-edit").validate({
			focusInvalid:true
			// focusCleanup: true
		});


		$(function() {

			initBrandSelect($('#typeId').val(),[[${goods.brandId}]]);
			resetProps($('#typeId').val());
			//设置商品规格
			// console.log("specDesc",$("#specDesc").val());
			// console.log("123",[[${goods.specDesc}]])
			editProductInfo($("#specDesc").val());

			$('.summernote').summernote({
				placeholder: '请输入内容',
				height: 192,
				lang : 'zh-CN',
				followingToolbar: false,
				callbacks: {
					onImageUpload: function (files) {
						sendFile(files, this);
					}
				}
			});
			var content = $("#intro").val();
			$('#editor').summernote('code', content);
		});


		function submitHandler() {
	        if ($.validate.form()) {
				var sHTML = $('.summernote').summernote('code');
				$("#intro").val(sHTML);
	            $.operate.save(prefix + "/edit", $('#form-goods-edit').serialize());
	        }
	    }

		/*用户管理-新增-选择部门树*/
		function selectGoodsTree() {

			// console.log("tree");
			var treeId = $("#treeId").val();
			var catId = $.common.isEmpty(treeId) ? "100" : $("#treeId").val();
			var url = ctx + "goods/goodsCat/selectCatTree/" + catId;
			// console.log("url:",url);
			var options = {
				title: '选择分类',
				width: "380",
				url: url,
				callBack: doSubmit
			};
			$.modal.openOptions(options);
		}

		function doSubmit(index, layero){
			var tree = layero.find("iframe")[0].contentWindow.$._tree;
			if ($.tree.notAllowParents(tree)) {
				var body = layer.getChildFrame('body', index);
				$("#treeId").val(body.find('#treeId').val());
				$("#treeName").val(body.find('#treeName').val());
				layer.close(index);

				//设置商品的类型
				var typeId = body.find('#typeId').val();
				$("#typeId").val(typeId);
				$("#typeName").val(body.find('#typeName').val());

				initBrandSelect(typeId);
				//查找类型是否有关联扩展属性和规格
				resetProps(typeId);
			}
		}

		function initBrandSelect(typeId,brandId) {
			$('[data-role="brand"]').empty('');
			//设置品牌
			$.ajax({
				url: ctx + "goods/brand/brandListByTypeId",
				type: 'POST',
				data: {
					typeId:typeId
				},
				success: function (result) {
					if (result.code == web_status.SUCCESS) {
						// console.log(result.data);
						if(result.data.lenth == 0){
							return;
						}
						$('[data-role="brand"]').append('<option value="">请选择品牌</option>');
						$.each(result.data,function(index, item) {
							$('[data-role="brand"]').append('<option value="'+ item.brandId +'">'+item.brandName+'</option>');
						});

						if(brandId){
							$('[data-role="brand"]').val(brandId);
						}
					}
				}

			});
		}


		function resetProps(typeId) {

			$.ajax({
				url: ctx + "goods/goodsType/getPropsAndSpecs",
				type: 'POST',
				data: {
					typeId:typeId,
					goodsId:$("#goodsId").val()
				},
				success: function (result) {
					$("#propsDiv").empty('');
					if (result.code == web_status.SUCCESS) {
						if(result.data.lenth == 0){
							return;
						}
						$.each(result.data.typePropsList,function(index, item) {
							// console.log(item.name)
							// console.log(item.typePropsValueList)

							var prop = "p" + (index + 1);
							var value = result.data.goods[prop];
							var select = buildSelect(item.name, prop, item.typePropsValueList, value);
							// console.log("select:",select)
							$("#propsDiv").append(select);
						});
					}
				}
			});
		}

		//动态添加下拉框
		function buildSelect(label, name, options, value) {

			var value = value || "";
			var select = '<div class="row">\
						<div class="col-md-6">\
							<div class="form-group">\
								<label class="col-sm-3 control-label"><span style="color: red; ">*</span>'+label+'：</label>\
								<div class="col-sm-9">\
									<select id="'+name+'" name="'+name+'"class="form-control noselect2"  required>\
										<option value="">请选择属性</option>';

			for (var i = 0; i < options.length; i++) {
				select += '<option value="' + options[i].propsValueId + '"' + (value == options[i].propsValueId ? "selected" : "") + '>' + options[i].name + '</option>';
			}

			select +='</select>\
							</div>\
						</div>\
			      </div>\
			  </div>';
			return select;
		}


		//重新编辑商品规格
		$('[data-role="product-edit"]').on("click",function () {
			var url = ctx + "goods/products/editProductSku?goodsId="+ [[${goodsId}]]+"&typeId="+ $("#typeId").val();
			console.log(url)
			var options = {
				title: '商品规格',
				width:900,
				url: url,
				btn:['关闭'],
				yes: function (index) {
					layer.close(index);
				}
			};
			$.modal.openOptions(options);
		});

		//重新编辑商品规格
		$('[data-role="product-close"]').on("click",function () {
			$.modal.confirm("确定要关闭规格么?", function () {
				$("#specDesc").val("");
				$("#specBtn").show();//显示规格按钮
				$("#specDiv").hide();//隐藏规格编辑信息
				$("#goodsBasic").show();//显示商品价格等信息
			});
		});

		function setSpecDesc(specDesc) {
			$("#specDesc").val(specDesc);
			editProductInfo(specDesc);
			$("#specBtn").hide();//隐藏规格按钮
			$("#specDiv").show();//显示规格编辑信息

		}

		function editProductInfo(specDesc) {
			if(specDesc != "" && specDesc != null){
				//编辑货品
				$("#specDiv").show()
				$('[data-role="spec-item"]').html("");
				$('[data-role="spec-tit"]').html("");
				var jsonSpecDesc = JSON.parse(specDesc);
				// console.log(jsonSpecDesc)
				var specNameArr = jsonSpecDesc.specNames.split(",")

				$('[data-role="spec-item"]').append('<li class="tit">已经启动的规格项:</li>');
				$.each(specNameArr, function (i, item) {
					$('[data-role="spec-item"]').append("<li>" + item + "</li>");
				});

				var result = '<p class="tit" data-role="spec-tit">已生成货品(' + jsonSpecDesc.num + ')</p>';
				$('[data-role="spec-tit"]').append(result);

				$("#goodsBasic").hide();//隐藏商品价格等信息
			}
		}

		$(function () {

			var imageUrls = [[${imageUrls}]];
			var imageUrlArray = [];
			if(imageUrls != ""){
				imageUrlArray = imageUrls.split(",");
			}

			var imageIds = [[${imageIds}]];

			var initialPreviewConfigStr = [[${initialPreviewConfig}]];
			console.log("json:",JSON.parse(initialPreviewConfigStr));

			$("#goodsPicture").fileinput({
				// 'theme': 'gly',
				uploadUrl: ctx + "common/upload",
				deleteUrl: ctx + "common/delete",
				showRemove: false,
				overwriteInitial: false,
				initialPreviewAsData: true,
				initialPreview: imageUrlArray,
				initialPreviewConfig:JSON.parse(initialPreviewConfigStr)
			}).on("fileuploaded", function (event, result) {
				var flag = $('.file-preview-frame').hasClass('is-selected');
				var imageIds = $('#imageIds').val();
				var imageId = result.response.data[0].imageId;

				if(!flag){
					$('.file-preview-frame').eq(0).addClass('is-selected');
				}

				if(imageIds !="" && imageIds != null){
					imageIds = imageIds+","+result.response.data[0].imageId;
				}else {
					imageIds = result.response.data[0].imageId
				}
				$('#imageDefaultId').val(imageId);
				$('#imageIds').val(imageIds);
			}).on("filepredelete", function(jqXHR) {
				// var abort = true;
				// if ($.modal.confirm("您确认要删除该图片么?",function () {
				// 	console.log("test")
				// }))
				// {
				// 	console.log("delete")
				// 	abort = true;
				// }
				// return abort; // you can also send any data/object that you can receive on `filecustomerror` event
				if (confirm("您确认要删除该图片么?")) {
					console.log("test123")
				}
			});

			//设置默认图片的勾选状态
			var imageDefaultId = [[${goods.imageDefaultId}]];
			// console.log("imageDefaultId:",imageDefaultId)
			// console.log("imageIds:",imageIds)
			if(imageDefaultId != "" && imageIds != ""){
				var pos = imageIds.split(",").indexOf(imageDefaultId);
				if(pos == -1){
					return;
				}
				console.log("pos:",pos)
				$.each($('.file-preview-frame'),function (index,obj) {
					if(index == pos){
						$(obj).addClass('is-selected').siblings().removeClass('is-selected');
					}
				})
			}
		});


		//点击切换默认图
		$(document).on('click', '.kv-file-content', function (e) {
			var flag = $(this).parent().hasClass('is-selected');
			if(flag){
				console.log("删除默认图")
			}else {
				console.log("删除非默认图")
				$(this).parent().addClass('is-selected').siblings().removeClass('is-selected');
				var index = $(this).parent().index();
				console.log("index:",index)

				var chosedVal = $('#imageIds').val().split(',')[index];
				$('#imageDefaultId').val(chosedVal);
			}
			return false;
		});

		//删除默认图的时候如果有其他图，设置其他图有默认图，如果没有则清空


		// 上传文件
		function sendFile(files, obj) {
			var formData = new FormData();
			for(f in files){
				formData.append("file", files[f]);
			}

			$.ajax({
				type: "POST",
				url: ctx + "common/upload",
				data: formData,
				cache: false,
				contentType: false,
				processData: false,
				dataType: 'json',
				success: function(result) {
					if (result.code == web_status.SUCCESS) {
						$.each(result.data,function(i,item){
							$(obj).summernote('editor.insertImage', item.url, item.fileName);
						});
					} else {
						$.modal.alertError(result.msg);
					}
				},
				error: function(error) {
					$.modal.alertWarning("图片上传失败。");
				}
			});
		}
	</script>
</body>
</html>
